<template>
  <el-dialog
    custom-class="second-dialog"
    title="选择应用"
    v-model="visibleDialog"
  >
    <el-form
      label-position="left"
      :model="ruleForm"
      ref="ruleFormRef"
      label-width="120px"
      inline
    >
      <el-form-item label="所属部门" prop="deptId">
        <OrgCascader v-model="ruleForm.deptId" />
      </el-form-item>
      <el-form-item label="所属应用" prop="appId">
        <el-select v-model="ruleForm.appId" placeholder="请选择所属应用">
          <el-option
            v-for="(item, index) in options"
            :key="index"
            :label="item.appName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visibleDialog = false"> 取消 </el-button>
        <el-button type="primary" @click="save"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script>
import { getAppListByOrg } from "@/api/application";
import OrgCascader from "@/components/OrgCascader/";
import { ref, reactive, watch, computed, defineComponent } from "vue";
export default defineComponent({
  name: "DeptSelect",
  props: {
    visible: {
      type: Boolean,
      require: true,
    },
    modelValue: {
      type: Object,
      default: () => {}
    },
  },
  components: { OrgCascader },
  emits: ["update:visible", "update:modelValue"],
  setup(props, { emit, slots }) {
    const ruleForm = reactive({
      deptId: null,
      appId: null,
    });
    const options = ref([]);
    const visibleDialog = computed({
      get: () => props.visible,
      set: (val) => emit("update:visible", val),
    });
    const save = () => {
      const appId =  ruleForm.appId
      let appName = null
      options.value.map(item => {
        item.id === appId && (appName = item.appName);
      })
      console.log(props.modelValue)
      console.log(appId)
      console.log(appName)
      const data = {
        ...props.modelValue,
        appId,
        appName
      }
      console.log(data)
      emit("update:modelValue", data)
      visibleDialog.value = false;
    };
    // 获取应用列表
    const getList = async (value) => {
      const { data } = await getAppListByOrg({ orgId: value });
      options.value = data;
    };
    watch(
      () => ruleForm.deptId,
      (value) => {
        getList(value);
      }
    );
    watch(
      () => visibleDialog,
      (value) => {
        if (value) {
          ruleForm.deptId = null;
          ruleForm.appId = null;
          options.value = [];
        }
      }
    );
    return {
      ruleForm,
      options,
      visibleDialog,
      save,
    };
  },
});
</script>
<style lang="scss">
</style>
